package com.rtx.wms.std.sku.handle;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.rtx.api.annotation.DataSourceAnnotation;
import com.rtx.common.EdiBeanUtils;
import com.rtx.edi.model.api.bo.ApiMappingInfoBo;
import com.rtx.wms.std.common.bean.Codelkup;
import com.rtx.wms.std.common.bean.WmsConstant;
import com.rtx.wms.std.common.mapper.CodelkupMapper;
import com.rtx.wms.std.ctclass.ClassHolder;
import com.rtx.wms.std.sku.bean.po.AltSku;
import com.rtx.wms.std.sku.bean.po.Sku;
import com.rtx.wms.std.sku.mapper.SkuConfigMapper;
import com.rtx.wms.std.sku.mapper.SkuMapper;
import com.rtx.wms.std.sku.service.AltSkuService;
import com.rtx.wms.std.sku.service.SkuService;
import com.rtx.wms.std.storer.service.StorerService;
import com.rtx.wms.std.validation.BaseValidation;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;

@SuppressWarnings("all")
@Service
public class SKUSchedulerHandleConfig extends BaseValidation{
	
	Logger log = LoggerFactory.getLogger(this.getClass());
	
	@Autowired
	SkuService skuService;
	
	@Autowired
	SkuMapper skuMapper;
	
	@Autowired
	SkuConfigMapper skuConfigMapper;
	
	@Autowired
	StorerService storerService;
	
	@Autowired
	CodelkupMapper codelkupMapper;
	
	@Autowired
	AltSkuService altSkuService;
	
    @Value("${rtx.datasource.name:enterprise,wmwhse1}")
    private String [] dataPeoperties;
    

    @DataSourceAnnotation
	public List<Sku> querySKU(String datasourcekey,ApiMappingInfoBo bo){
		QueryWrapper<Sku> qw = new QueryWrapper<Sku>();
		qw.eq("ediflag", "P");
		qw.last("limit 500");
		return convertToConfigSku(bo,qw);
	}
    
    private List<Sku> convertToConfigSku(ApiMappingInfoBo bo,QueryWrapper<Sku> qw){
    	List<Sku> head = new ArrayList<>();
    	try {
    		String apiid =  bo.getTargetApi().getId()+"";
    		Map<String,Class> map = ClassHolder.apiconfigClassMap.get(apiid);

    		if(map != null && map.get("main") != null) {
    			Class headclass = map.get("main");
    			qw.select(EdiBeanUtils.getCoulmns(headclass));
    			List<Map<String, Object>> oriData = skuService.getBaseMapper().selectMaps(qw);
    			for(Map<String, Object> dataMap:oriData) {
    				Sku sku =(Sku) EdiBeanUtils.copyFields(dataMap, headclass);
    				head.add(sku);
    			}
    		}else {
    			head = skuService.list(qw);
    		}
    	} catch (Exception e) {
    		e.printStackTrace();
    	}

    	return head;
    }
	
	@DataSourceAnnotation
	public void distributeSKU(String datasourcekey,Sku sku){
		QueryWrapper<Sku> qw = new QueryWrapper<Sku>();
		qw.eq("sku", sku.getSku());
		qw.eq("storerkey", sku.getStorerkey());
		List<Sku> list = skuMapper.selectList(qw);
		
		if(list == null || list.size() <1) {
			sku.setSerialkey(null);
			sku.setWhseid(datasourcekey.toUpperCase());
			skuConfigMapper.rtxconfigColumnsSave(sku);
		}else {
			Sku where = new Sku();
			where.setSku(sku.getSku());
			where.setStorerkey(sku.getStorerkey());
			
			Sku dbSKu = list.get(0);
			
			if(StringUtils.hasLength(dbSKu.getLottablevalidationkey())) {
				sku.setLottablevalidationkey(null);
			}
			if(StringUtils.hasLength(dbSKu.getPackkey())) {
				sku.setPackkey(null);
			}
			if(StringUtils.hasLength(dbSKu.getStrategykey())) {
				sku.setStrategykey(null);
			}
			if(StringUtils.hasLength(dbSKu.getPutawaystrategykey())) {
				sku.setPutawaystrategykey(null);
			}
			if(dbSKu.getStdgrosswgt() !=null) {
				sku.setStdgrosswgt(null);
			}
			
			sku.setSerialkey(null);
			sku.setWhseid(datasourcekey.toUpperCase());
			
			skuConfigMapper.rtxconfigUpdate(sku, where);
		}
	}
	
	@DataSourceAnnotation
	public void updStatus(String datasourcekey,String msg,Sku sku) {
		String status ="";
		String notNullMsg = Optional.ofNullable(msg).orElse("");
		String msgUseable = notNullMsg.length()>499?notNullMsg.substring(0,200):notNullMsg;
		
		if("OK".equals(msg)) {
			status =WmsConstant.SUCCESS_FLAG;
		}else {
			status =WmsConstant.FAIL_FLAG;
		}
		
		skuMapper.updStatus(status, msgUseable, sku.getSku());
	}
	
	/**
	 * 设置 默认拣货策略  默认上架策略
	 * @param datasourcekey
	 * @param sku
	 */
	@DataSourceAnnotation
	public void handleSKUSTRATEGY(String datasourcekey,Sku sku) {
		LambdaQueryWrapper<Codelkup> lqw = Wrappers.lambdaQuery();
		lqw
		.eq(Codelkup::getListname, "storerWarehouse")
		.eq(Codelkup::getCode, sku.getStorerkey());
		
		Codelkup config =	codelkupMapper.selectOne(lqw);
		if(null == config) {
			throw new RuntimeException("企业级系统代码storerWarehouse-未配置-code-"+sku.getStorerkey()+"分配策略");
		}
		sku.setStrategykey(config.getUdf3());
		sku.setPutawaystrategykey(config.getUdf2());
	}
	
	/**
	 * 	写入或者更新货品别名表
	 * @param datasourcekey
	 * @param sku
	 */
	public void handleAltesku(String datasourcekey,Sku sku) {
		if(StringUtils.hasLength(sku.getAltsku())) {
			AltSku altsku = mappingAltsku(sku);
			
			altSkuService.addAndUpdAltSku(datasourcekey, altsku);
		}
	}
	
	public AltSku mappingAltsku(Sku sku) {
		AltSku a = new AltSku();
		a.setSku(sku.getSku());
		a.setAltsku(sku.getAltsku());
		a.setStorerkey(sku.getStorerkey());
		a.setPackkey("STD");
		a.setDefaultuom("EA");
		a.setType("2");
		a.setAdddate(LocalDateTime.now());
		a.setEditdate(LocalDateTime.now());
		a.setAddwho("api");
		a.setEditwho("api");
		return a;
	}
	
}
